package com.example.llm;

import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.prefs.Preferences;

public class ChatSessionManager {
    private List<ChatSession> sessions;
    private ChatSession currentSession;
    private final Path sessionsDir;
    private final Preferences prefs;

    public ChatSessionManager() {
        prefs = Preferences.userNodeForPackage(ChatSessionManager.class);
        String userHome = System.getProperty("user.home");
        sessionsDir = Paths.get(userHome, ".myllm", "sessions");
        sessions = new ArrayList<>();
        
        try {
            // 确保会话目录存在
            if (!Files.exists(sessionsDir)) {
                Files.createDirectories(sessionsDir);
                System.out.println("创建会话目录: " + sessionsDir);
            }
            loadSessions();
        } catch (IOException e) {
            System.err.println("创建会话目录时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
        
        if (sessions.isEmpty()) {
            createNewSession();
        }
        
        String currentSessionId = prefs.get("currentSessionId", null);
        if (currentSessionId != null) {
            currentSession = sessions.stream()
                .filter(s -> s.getId().equals(currentSessionId))
                .findFirst()
                .orElse(sessions.get(0));
        } else {
            currentSession = sessions.get(0);
        }
    }

    public ChatSession createNewSession() {
        // 检查是否已经存在"新会话"
        Optional<ChatSession> existingSession = sessions.stream()
            .filter(s -> "新会话".equals(s.getTitle()))
            .findFirst();
            
        if (existingSession.isPresent()) {
            // 如果已存在"新会话"，直接返回该会话
            System.out.println("已存在新会话，返回现有会话");
            return existingSession.get();
        }

        // 如果不存在，创建新会话
        ChatSession session = new ChatSession();
        sessions.add(session);
        saveSession(session);
        System.out.println("创建新会话: " + session.getId());
        return session;
    }

    public void setCurrentSession(ChatSession session) {
        this.currentSession = session;
        prefs.put("currentSessionId", session.getId());
    }

    public ChatSession getCurrentSession() {
        return currentSession;
    }

    public List<ChatSession> getAllSessions() {
        return new ArrayList<>(sessions);
    }

    public void deleteSession(ChatSession session) {
        if (session == null) {
            System.out.println("尝试删除空会话");
            return;
        }

        // 如果是最后一个会话且标题是"新会话"，不允许删除
        if (sessions.size() == 1 && "新会话".equals(session.getTitle())) {
            System.out.println("不能删除唯一的新会话");
            return;
        }

        System.out.println("正在删除会话: " + session.getTitle());

        // 从内存中移除会话
        boolean removed = sessions.remove(session);
        if (!removed) {
            System.out.println("会话不在列表中");
            return;
        }

        // 如果要删除的是当前会话，先找到下一个可用的会话
        if (session == currentSession) {
            Optional<ChatSession> nextSession = sessions.stream()
                .filter(s -> !s.equals(session))
                .findFirst();
                
            if (nextSession.isPresent()) {
                currentSession = nextSession.get();
                prefs.put("currentSessionId", currentSession.getId());
                System.out.println("切换到下一个会话: " + currentSession.getTitle());
            } else {
                // 如果没有其他会话，创建新会话
                currentSession = createNewSession();
                System.out.println("创建新会话: " + currentSession.getTitle());
            }
        }

        // 删除会话文件
        try {
            Path sessionFile = getSessionFile(session);
            if (Files.exists(sessionFile)) {
                Files.delete(sessionFile);
                System.out.println("删除会话文件成功");
            } else {
                System.out.println("会话文件不存在");
            }
        } catch (IOException e) {
            System.err.println("删除会话文件失败: " + e.getMessage());
        }
    }

    public void saveSession(ChatSession session) {
        try (ObjectOutputStream oos = new ObjectOutputStream(
                Files.newOutputStream(getSessionFile(session)))) {
            oos.writeObject(session);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void loadSessions() {
        try {
            if (!Files.exists(sessionsDir)) {
                System.out.println("会话目录不存在");
                return;
            }
            
            List<ChatSession> loadedSessions = new ArrayList<>();
            ChatSession newSession = null;
            
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(sessionsDir, "*.session")) {
                for (Path file : stream) {
                    try (ObjectInputStream ois = new ObjectInputStream(Files.newInputStream(file))) {
                        ChatSession session = (ChatSession) ois.readObject();
                        if (session != null && session.getId() != null) {
                            // 检查是否是"新会话"
                            if ("新会话".equals(session.getTitle())) {
                                if (newSession == null) {
                                    newSession = session;
                                    loadedSessions.add(session);
                                    System.out.println("加载新会话: " + session.getId());
                                } else {
                                    // 如果已经有"新会话"，删除这个重复的会话文件
                                    System.out.println("发现重复的新会话，删除: " + file);
                                    try {
                                        Files.delete(file);
                                    } catch (IOException ex) {
                                        System.err.println("删除重复的新会话文件失败: " + ex.getMessage());
                                    }
                                }
                            } else {
                                loadedSessions.add(session);
                                System.out.println("加载会话: " + session.getTitle() + " (ID: " + session.getId() + ")");
                            }
                        }
                    } catch (InvalidClassException e) {
                        System.err.println("会话文件版本不兼容，将删除: " + file);
                        try {
                            Files.delete(file);
                        } catch (IOException ex) {
                            System.err.println("删除不兼容的会话文件失败: " + ex.getMessage());
                        }
                    } catch (Exception e) {
                        System.err.println("加载会话文件失败: " + file + ", 错误: " + e.getMessage());
                        try {
                            Files.delete(file);
                        } catch (IOException ex) {
                            System.err.println("删除损坏的会话文件失败: " + ex.getMessage());
                        }
                    }
                }
            }
            
            // 更新会话列表
            sessions = loadedSessions;
            
            // 按最后更新时间排序
            sessions.sort((a, b) -> b.getLastUpdateTime().compareTo(a.getLastUpdateTime()));
            
            // 如果没有"新会话"，创建一个
            if (newSession == null) {
                System.out.println("未找到新会话，创建新会话");
                newSession = createNewSession();
            }
            
            System.out.println("共加载 " + sessions.size() + " 个会话");
            
        } catch (IOException e) {
            System.err.println("加载会话时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private Path getSessionFile(ChatSession session) {
        return sessionsDir.resolve(session.getId() + ".session");
    }

    public void updateSessionTitle(ChatSession session, String title) {
        session.setTitle(title);
        saveSession(session);
    }

    public void pinSession(ChatSession session, boolean pinned) {
        session.setPinned(pinned);
        saveSession(session);
        sessions.sort((a, b) -> {
            if (a.isPinned() != b.isPinned()) {
                return Boolean.compare(b.isPinned(), a.isPinned());
            }
            return b.getLastUpdateTime().compareTo(a.getLastUpdateTime());
        });
    }
} 